package com.eims.sls_app.ui;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;
import com.bx.pay.BXPay;
import com.bx.pay.PayInfo;
import com.bx.pay.Payment;
import com.bx.pay.backinf.PayCallback;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.MD5Utils;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyToast;
import com.hmjr.wxp.util.Common;
import com.switfpass.pay.MainApplication;
import com.switfpass.pay.activity.PayPlugin;
import com.switfpass.pay.bean.RequestMsg;
import com.switfpass.pay.utils.MD5;
import com.switfpass.pay.utils.SignUtils;
import com.switfpass.pay.utils.Util;
import com.switfpass.pay.utils.XmlUtils;

public class AmountOfChargeTonew extends MyBaseActivity implements OnClickListener {
	public final static String TAG = "AmountOfCharge";
	public String feeName = "好球充值";
	public String feePrice = "";
	public String feeDesc = "好球充值";
	public String Key = "4297f44b13955235245b2497399d7a93";
	// public String Key_kefu = "4297f44b13955235245b2497399d7a93";
	public ImageButton btn_back;
	public EditText recahge_et_money;
	// 立即充值
	public Button recharge_btn_ok;

	public static Context mContext;
	// 充值类型1,银联2,支付宝3,微信4.支付宝快捷支付,5 支付宝快捷支付推荐，6.QQ钱包
	public int type;
	// Request
	private Request jsonObjectRequest;
	private String RE = "tb_Regesitor";
	private String DOWN = "tb_DownLoadKey";
	// 充值金额
	private double dMoney;
	// 最小充值金额
	private double Min;
	// 订单号
	public String outer_no;

	public RelativeLayout rlInput_01, rlInput_02, rlInput_03, rlInput_04;
	public TextView tvMoneyNum_01, tvMoneyNum_02, tvMoneyNum_03, tvMoneyNum_04;

	
	private String orderNo;
    private boolean isGetBackPayInfo = false;
    private ProgressDialog pd;
    private MyHandler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_amount_of_charge);
		mContext = AmountOfChargeTonew.this;
		 handler = new MyHandler();
		InitView();
		Bundle bundle = getIntent().getExtras();
		type = bundle.getInt("Type");
		if (type == 4) {
			// recharge_tv_tishi.setText("温馨提示：充值免手续费，充值金额需100%消费，奖金提款不受限制" + "\n" +
			// "如未打开支付宝app,请结束支付宝进程再试一次。");
		}

	}

	private void InitView() {
		// TODO Auto-generated method stub

		rlInput_01 = (RelativeLayout) findViewById(R.id.rl_buy_01);
		rlInput_02 = (RelativeLayout) findViewById(R.id.rl_buy_02);
		rlInput_03 = (RelativeLayout) findViewById(R.id.rl_buy_03);
		rlInput_04 = (RelativeLayout) findViewById(R.id.rl_buy_04);

		tvMoneyNum_01 = (TextView) findViewById(R.id.tv_num_buy_01);
		tvMoneyNum_02 = (TextView) findViewById(R.id.tv_num_buy_02);
		tvMoneyNum_03 = (TextView) findViewById(R.id.tv_num_buy_03);
		tvMoneyNum_04 = (TextView) findViewById(R.id.tv_num_buy_04);

		rlInput_01.setOnClickListener(this);
		rlInput_02.setOnClickListener(this);
		rlInput_03.setOnClickListener(this);
		rlInput_04.setOnClickListener(this);

		btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);
		recahge_et_money = (EditText) findViewById(R.id.recahge_et_money);
		recharge_btn_ok = (Button) findViewById(R.id.recharge_btn_ok);
		// recharge_tv_tishi = (TextView) findViewById(R.id.recharge_tv_tishi);
		recharge_btn_ok.setOnClickListener(this);

		recahge_et_money.addTextChangedListener(new EditChangedListener());

		rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
		rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
		rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
		rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
		tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
		tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

		tvMoneyNum_03.setTextColor(getResources().getColor(R.color.white));
		tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
		//recahge_et_money.setText("888.88");

		recahge_et_money.setSelection(recahge_et_money.getText().toString().length());

	}

	class EditChangedListener implements TextWatcher {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {

			if (recahge_et_money.getText().toString().equals("50") || recahge_et_money.getText().toString().equals("100")
					|| recahge_et_money.getText().toString().equals("500")
					|| recahge_et_money.getText().toString().equals("1000")) {

			}else {

			rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

			tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.rl_buy_01:
			rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
			rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			tvMoneyNum_01.setTextColor(getResources().getColor(R.color.white));
			tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

			tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
			recahge_et_money.setText("50");

			recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
			break;
		case R.id.rl_buy_02:
			rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
			rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_02.setTextColor(getResources().getColor(R.color.white));

			tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
			recahge_et_money.setText("100");

			recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
			break;
		case R.id.rl_buy_03:
			rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
			rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

			tvMoneyNum_03.setTextColor(getResources().getColor(R.color.white));
			tvMoneyNum_04.setTextColor(getResources().getColor(R.color.main_red));
			recahge_et_money.setText("500");

			recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
			break;
		case R.id.rl_buy_04:
			rlInput_01.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_02.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_03.setBackgroundResource(R.drawable.buy_rl_money_input_border);
			rlInput_04.setBackgroundResource(R.drawable.buy_rl_money_input_border_on);
			tvMoneyNum_01.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_02.setTextColor(getResources().getColor(R.color.main_red));

			tvMoneyNum_03.setTextColor(getResources().getColor(R.color.main_red));
			tvMoneyNum_04.setTextColor(getResources().getColor(R.color.white));
			recahge_et_money.setText("1000");

			recahge_et_money.setSelection(recahge_et_money.getText().toString().length());
			break;
		case R.id.btn_back:
			AmountOfChargeTonew.this.finish();
			break;
		case R.id.recharge_btn_ok:

			// 获取金额
			// if(ClickFilter.filter()) return;
			feePrice = recahge_et_money.getText().toString();

			if (feePrice.length() > 0 && !feePrice.equals("")) {
				double parseInt = Double.parseDouble(feePrice);
				if (parseInt >= 2) {

					// 获取订单号
					MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeTonew.this);
					if (type == 4) {
//						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_kefu,
//								new Response.Listener<String>() {
//									@Override
//									public void onResponse(String tn) {
//										try {
//											outer_no = tn;
//											if (!outer_no.equals("") && outer_no.length() > 0) {
//												Log.i(TAG,
//														"获取金额" + App.user.getUid() + "|" + outer_no + "|" + "支付宝");
//												pay2(feePrice, App.user.getUid() + "|" + outer_no + "|" + "支付宝");
//
//											} else {
//												MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
//											}
//										} catch (Exception e) {
//											e.printStackTrace();
//											if (RequestUtil.DEBUG) {
//
//											}
//											MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
//										}
//									}
//								}, new Response.ErrorListener() {
//
//									@Override
//									public void onErrorResponse(VolleyError error) {
//
//										if (RequestUtil.DEBUG) {
//											String className = error.getClass().getName();
//											Log.i(TAG, "获取订单出错---" + error.getMessage());
//										}
//										MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
//									}
//								}) {
//							@Override
//							protected Map<String, String> getParams() throws AuthFailureError {
//								/*
//								 * String[] names = { "userID", "money" ,"type"}; String values[] = {
//								 * App.user.getUid(), feePrice ,type+""};
//								 */
//								String[] names = { "userID", "money" };
//								String values[] = { App.user.getUid(), feePrice };
//								if (RequestUtil.DEBUG)
//									;
//								Map<String, String> params = new HashMap<String, String>();
//								for (int i = 0; i < names.length; i++) {
//									params.put(names[i], values[i]);
//								}
//								return params;
//							}
//						};
//
//					
					 pay2(feePrice, App.user.getUid() );
					} else if (type == 7) {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_kefu,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {
												Log.i(TAG,
														"获取金额" + App.user.getUid() + "|" + outer_no + "|" + "微信");
												testValidCard(feePrice,
														App.user.getUid() + "|" + outer_no + "|" + "微信");

											} else {
												MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {
								/*
								 * String[] names = { "userID", "money" ,"type"}; String values[] = {
								 * App.user.getUid(), feePrice ,type+""};
								 */
								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};
					} else if (type == 5 || type == 6) {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_xinye,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {

												pay_xingye(feeName, feePrice, feeDesc,
														App.user.getUid() + "|" + outer_no);

											} else {
												MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {

								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};

					} else {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {

												pay(feeName, feePrice, feeDesc,
														App.user.getUid() + "|" + outer_no);

											} else {
												MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {

								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};

					}

					jsonObjectRequest.setShouldCache(false);// 是否设置缓存
					mySingleton.addToRequestQueue(jsonObjectRequest);
				} else {
					MyToast.getToast(AmountOfChargeTonew.this, "充值金额小于2元!").show();
				}
			} else {
				Log.i(TAG, "获取金额" + recahge_et_money.getHint().toString());
				// MyToast.getToast(AmountOfCharge.this, "请输入充值金额!").show();
				getPay();
			}

			// if(ClickFilter.filter()) return;
			break;

		default:
			break;
		}
	}

	// 新的微信支付
	public void testValidCard(final String feePrice, final String other_no) {
		try {
			MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeTonew.this);
			// 发送 POST 请求
			MD5Utils md5Utils = new MD5Utils();
			Map<String, String> map = new HashMap<String, String>();
			String orderDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			int a = Integer.parseInt(feePrice) * 100;
			map.put("subMchId", "000000294577");
			map.put("orderDate", orderDate);
			map.put("body", "好球cp");
			map.put("amount", "0.1");
			map.put("productId", "好球cp");
			map.put("notifyUrl", "http://hqcz.ucaipiao.com/KPayConfirm.aspx");
			map.put("userid", Common.userid);
			/** 参与验签的字段 */
			String sign = md5Utils.getSignParam(map);
			System.out.println("计算签名的报文为：" + sign);
			sign = md5Utils.getKeyedDigest(sign, Common.key);
			/** 上送的值为 */
			map.put("sign", sign);
			map.put("pay_number", other_no);
			map.put("orderCode", Common.kl_WXPay);
			String result = md5Utils.getSignParam(map);
			System.out.println("上送的报文为：" + result);

			// String sr = HttpClientUtil.sendPostRequest(Common.URL, map);
			// System.out.println(sr);
			// Map ValidCard = JsonUtil.jsonToMap(sr);
			// System.out.println(ValidCard);
			Log.i(TAG, "提交的数据" + result);
			jsonObjectRequest = new StringRequest(Request.Method.GET, App.PAY_KEFU + "?" + result,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							Log.i(TAG, "返回的数据" + tn);
							try {
								JSONObject jsonObject = new JSONObject(tn);
								String respCode = jsonObject.optString("respCode");
								String respInfo = jsonObject.optString("respInfo");
								if (respCode.equals("000000")) {
									String QRcodeURL = jsonObject.optString("QRcodeURL");

									Uri uri = Uri.parse(QRcodeURL);
									Intent intent = new Intent(Intent.ACTION_VIEW, uri);
									startActivity(intent);
								} else {
									MyToast.getToast(mContext, respInfo);
								}
							} catch (JSONException e) {

								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
						}
					});

			jsonObjectRequest.setShouldCache(false);// 是否设置缓存
			mySingleton.addToRequestQueue(jsonObjectRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void pay2(final String feePrice, final String other_no) {
		   MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeTonew.this);

	        try {
	            int a = Integer.parseInt(feePrice);
	            // 发送 POST 请求
//	            MD5Utils md5Utils = new MD5Utils();
//	            String txnTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//	            Map params = new HashMap();
	//
//	            params.put("merId", "929020095023273");
//	            params.put("merKey", "rSF2NztFrazg3xxvTDjdJjZjyG7g8Z7B");
//	            params.put("amount", "0.1");
//	            params.put("notifyUrl", "http://lmcz.ucaipiao.com/KPayConfirm.aspx");
//	            params.put("txnTime", txnTime);
//	            params.put("pageNotifyUrl", "http://www.baidu.com");
//	            params.put("body", "好球彩");
//	            params.put("userid", Common.userid);
//	            System.out.println("=====" + params);
//	            /** 参与验签的字段 */
//	            String sign = md5Utils.getSignParam(params);
//	            System.out.println("计算签名的报文为：" + sign);
//	            sign = md5Utils.getKeyedDigest(sign, Common.key);
//	            /** 上送的值为 */
//	            params.put("sign", sign);
//	            params.put("orderCode", Common.an_newConsume);
//	            params.put("pay_number", other_no);
//	            orderNo = other_no;
	//
//	            String result = md5Utils.getSignParam(params);
//	            System.out.println("上送的报文为：" + result);
//				String sr = HttpClientUtil.sendPostRequest(Common.URL, params);
//				System.out.println(sr);
//	            pd = BaseHelper.showProgress(AmountOfChargeTonew.this, "", "加载中...", true, false);
//	            Log.i(TAG, "提交的数据" + result);
	            jsonObjectRequest = new StringRequest(Request.Method.GET, "http://hqcz.ucaipiao.com/PayKF.aspx?money="+a+"&userID="+App.user.getUid(),
	                    new Response.Listener<String>() {
	                        @Override
	                        public void onResponse(String tn) {
	                            Log.i(TAG, "返回的数据" + tn);

	                            try {
	                                JSONObject jsonObject = new JSONObject(tn);
	                                String respCode = jsonObject.optString("respCode");
	                                String respInfo = jsonObject.optString("respInfo");
	                                String  payNum=jsonObject.optString("pay_number");
	                                if (respCode.equals("1001")) {

	                                    isGetBackPayInfo = true;
									orderNo=payNum;
	                                    String QRcodeURL = jsonObject.optString("payUrl");

	                                    Uri uri = Uri.parse(QRcodeURL);
	                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
	                                    startActivity(intent);
	                                } else {
	                                    MyToast.getToast(mContext, respInfo);
	                                }
	                            } catch (JSONException e) {

	                                e.printStackTrace();
	                            }
	                        }
	                    }, new Response.ErrorListener() {

	                @Override
	                public void onErrorResponse(VolleyError error) {

	                    if (RequestUtil.DEBUG) {
	                        String className = error.getClass().getName();
	                        Log.i(TAG, "获取订单出错---" + error.getMessage());
	                    }
	                    MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
	                }
	            });

	            jsonObjectRequest.setShouldCache(false);// 是否设置缓存
	            mySingleton.addToRequestQueue(jsonObjectRequest);
	//

	        } catch (Exception e) {
	            e.printStackTrace();
	        }


	}
	 protected void onResume() {
	        // TODO Auto-generated method stub
	        super.onResume();

	        if (isGetBackPayInfo) {
	            isGetBackPayInfo = false;
	            pd = BaseHelper.showProgress(AmountOfChargeTonew.this, "", "加载中...", true, false);
	            handler.sendEmptyMessageDelayed(2, 3000);
	        } else {
	            isGetBackPayInfo = false;
	        }
	    }

	    class MyHandler extends Handler {
	        @Override
	        public void handleMessage(Message msg) {
	            if (pd != null) {
	                pd.dismiss();
	            }
	            switch (msg.what) {

	                case 2:
	                    testValidCard();
	                    break;

	                default:
	                    break;
	            }

	            super.handleMessage(msg);
	        }

	    }

	    public void testValidCard() {
	        MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeTonew.this);
	        try {
	            String txnTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	            // 发送 POST 请求
//	            com.hmjr.wxp.util.MD5Utils md5Utils = new com.hmjr.wxp.util.MD5Utils();
//	            Map<String, String> map = new HashMap<String, String>();
////				map.put("orderId","an201802081717328026252679251");
//	            map.put("merId", "929020095023273");
//	            map.put("merKey", "rSF2NztFrazg3xxvTDjdJjZjyG7g8Z7B");
//	            map.put("userid", Common.userid);
//	            /** 参与验签的字段 */
//	            String sign = md5Utils.getSignParam(map);
//	            System.out.println("计算签名的报文为：" + sign);
//	            sign = md5Utils.getKeyedDigest(sign, Common.key);
//	            /** 上送的值为 */
//	            map.put("sign", sign);
//	            map.put("orderCode", Common.an_newConsumeQuery);
//	            map.put("pay_number", orderNo);
//	            String result = md5Utils.getSignParam(map);
//	            System.out.println("上送的报文为：" + result);
//	            Log.i(TAG, "提交的数据" + result);
	            jsonObjectRequest = new StringRequest(Request.Method.GET, "http://hqcz.ucaipiao.com/KFQuery.aspx?orderId="+orderNo,
	                    new Response.Listener<String>() {
	                        @Override
	                        public void onResponse(String tn) {
	                            Log.i(TAG, "返回的数据" + tn);
	                            try {
	                                JSONObject jsonObject = new JSONObject(tn);
	                                String respCode = jsonObject.optString("respCode");
	                                String respInfo = jsonObject.optString("respInfo");
	                                if (respCode.equals("1001")) {
	                                    Toast.makeText(AmountOfChargeTonew.this, respInfo, Toast.LENGTH_SHORT).show();
	                                    finish();

	                                } else {
	                                    Toast.makeText(AmountOfChargeTonew.this, "支付失败", Toast.LENGTH_SHORT).show();
	                                }

	                            } catch (JSONException e) {

	                                e.printStackTrace();
	                            }
	                        }
	                    }, new Response.ErrorListener() {

	                @Override
	                public void onErrorResponse(VolleyError error) {

	                    if (RequestUtil.DEBUG) {
	                        String className = error.getClass().getName();
	                        Log.i(TAG, "获取订单出错---" + error.getMessage());
	                    }
	                    MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
	                }
	            });

	            jsonObjectRequest.setShouldCache(false);// 是否设置缓存
	            mySingleton.addToRequestQueue(jsonObjectRequest);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	private void getPay() {

		MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeTonew.this);
		if (type == 4) {
		    pay2("888.88", App.user.getUid() );
		} else if (type == 5 || type == 6) {
			jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_xinye,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							try {
								outer_no = tn;
								if (!outer_no.equals("") && outer_no.length() > 0) {

									pay_xingye(feeName, "888.88", feeDesc, App.user.getUid() + "|" + outer_no);

								} else {
									MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								if (RequestUtil.DEBUG) {

								}
								MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
						}
					}) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {

					String[] names = { "userID", "money" };
					String values[] = { App.user.getUid(), "100" };
					if (RequestUtil.DEBUG)
						;
					Map<String, String> params = new HashMap<String, String>();
					for (int i = 0; i < names.length; i++) {
						params.put(names[i], values[i]);
					}
					return params;
				}
			};
		} else {
			jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							try {
								outer_no = tn;
								if (!outer_no.equals("") && outer_no.length() > 0) {

									pay(feeName, "888.88", feeDesc, App.user.getUid() + "|" + outer_no);

								} else {
									MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败亲重新操作!").show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								if (RequestUtil.DEBUG) {

								}
								MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeTonew.this, "获取订单失败").show();
						}
					}) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {

					String[] names = { "userID", "money" };
					String values[] = { App.user.getUid(), "100" };
					if (RequestUtil.DEBUG)
						;
					Map<String, String> params = new HashMap<String, String>();
					for (int i = 0; i < names.length; i++) {
						params.put(names[i], values[i]);
					}
					return params;
				}
			};

		}
		jsonObjectRequest.setShouldCache(false);// 是否设置缓存
		mySingleton.addToRequestQueue(jsonObjectRequest);
	}

	/**
	 * 调用支付接口示例方法--动态计费点
	 * 
	 * @param name
	 *            商品名称
	 * @param name
	 *            商品价格，单位为元，精确到两位小数
	 * @param name
	 *            商品描述，可以为空
	 */
	private void pay(String name, String price, String desc, String outer_no) {
		recommendbody = name;// 商品名称
		recommendprice = price;// 价格
		recommenddes = desc;// 商品描述
		recommendattach = outer_no;
		Log.e(TAG, outer_no);
		// 注意：传入的mContext值类型需是Activity
		BXPay bxPay = new BXPay(AmountOfChargeTonew.this);
		Map<String, String> devPrivate = new HashMap<String, String>();
		// String outer_no = String.valueOf(System.currentTimeMillis());

		devPrivate.put("cpparam", outer_no);// 开发者自定义参数

		bxPay.setDevPrivate(devPrivate);// setDevPrivate方式是可选，非必须
		// 商品参数
		PayInfo payInfo = new PayInfo();
		payInfo.setName(name) // 商品名称
				.setPrice(price) // 商品价格
				.setDesc(desc);// 商品描述，可以为空

		if (type == 1) {
			if (NetWork.isConnect(AmountOfChargeTonew.this)) {
				payInfo.addPayment(Payment.UPMPBANK);// 银联支付
			} else {
				MyToast.getToast(AmountOfChargeTonew.this, "网络连接异常，请检查网络").show();
			}

		} else if (type == 2) {
			if (NetWork.isConnect(AmountOfChargeTonew.this)) {
				payInfo.addPayment(Payment.ALIPAY); // 支付宝支付
			} else {
				MyToast.getToast(AmountOfChargeTonew.this, "网络连接异常，请检查网络").show();
			}

		} else if (type == 3) {
			if (NetWork.isConnect(AmountOfChargeTonew.this)) {
				Log.i(TAG, "微信支付");
				payInfo.addPayment(Payment.WXPAY);// 微信支付

			} else {
				MyToast.getToast(AmountOfChargeTonew.this, "网络连接异常，请检查网络").show();
			}
			
//			Intent intent_wxpay = new Intent();
//			Bundle bundle_wxpay = new Bundle();
//			intent_wxpay.setClass(AmountOfChargeTonew.this,
//					WebViewPayACtivity.class);
//			bundle_wxpay.putString("price", price);
//			bundle_wxpay.putString("outer_no", outer_no);
//			intent_wxpay.putExtras(bundle_wxpay);
//			startActivity(intent_wxpay);
		}
		// else if (type == 5) {
		// if (NetWork.isConnect(AmountOfCharge.this)) {
		// new GetPrepayIdTask().execute();// 支付宝快捷支付（推荐）
		//
		// } else {
		// MyToast.getToast(AmountOfCharge.this, "网络连接异常，请检查网络").show();
		// }
		//
		// } else if (type == 6) {
		// if (NetWork.isConnect(AmountOfCharge.this)) {
		// new GetPrepayIdTask().execute();// QQ钱包支付
		//
		// } else {
		// MyToast.getToast(AmountOfCharge.this, "网络连接异常，请检查网络").show();
		// }
		// }
		else {
			// 调用微派支付接口
			bxPay.pay(payInfo, new PayCallback() {

				@Override
				public void pay(Map resultInfo) {
					System.out.println("正在充值");
					final String payBank;
					String result = (String) resultInfo.get("result");
					String payType = (String) resultInfo.get("payType");
					String payCode = (String) resultInfo.get("payCode");
					String price = (String) resultInfo.get("price");
					String logCode = (String) resultInfo.get("logCode");
					String showMsg = (String) resultInfo.get("showMsg");
					System.out.println("支付信息" + showMsg);

					// //以下是显示支付结果示例代码，仅供参考
					if (showMsg.equals("支付成功!祝您游戏愉快！")) {
						MyToast.getToast(AmountOfChargeTonew.this, "支付成功!").show();
						AmountOfChargeTonew.this.finish();
						Intent intent = new Intent(getApplicationContext(), MainActivity.class);
						AmountOfChargeTonew.this.startActivity(intent);
						MainActivity.toCenter();
					} else {
						MyToast.getToast(AmountOfChargeTonew.this, "支付失败!").show();

					}
				}
			});
		}
	}

	/**
	 * 调用兴业支付接口示例方法--动态计费点
	 * 
	 * @param name
	 *            商品名称
	 * @param name
	 *            商品价格，单位为元，精确到两位小数
	 * @param name
	 *            商品描述，可以为空
	 */
	private void pay_xingye(String name, String price, String desc, String outer_no) {
		recommendbody = name;// 商品名称
		recommendprice = price;// 价格
		recommenddes = desc;// 商品描述
		recommendattach = outer_no;
		Log.e(TAG, outer_no);

		if (type == 5) {
			if (NetWork.isConnect(AmountOfChargeTonew.this)) {
				new GetPrepayIdTask().execute();// 支付宝快捷支付（推荐）

			} else {
				MyToast.getToast(AmountOfChargeTonew.this, "网络连接异常，请检查网络").show();
			}

		} else if (type == 6) {
			if (NetWork.isConnect(AmountOfChargeTonew.this)) {
				new GetPrepayIdTask().execute();// QQ钱包支付

			} else {
				MyToast.getToast(AmountOfChargeTonew.this, "网络连接异常，请检查网络").show();
			}
		}
	}

	private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {

		private ProgressDialog dialog;

		private String accessToken;

		public GetPrepayIdTask(String accessToken) {
			this.accessToken = accessToken;
		}

		public GetPrepayIdTask() {
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(AmountOfChargeTonew.this, getString(R.string.app_tip),
					getString(R.string.getting_prepayid));
		}

		@Override
		protected void onPostExecute(Map<String, String> result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			if (result == null) {
				Toast.makeText(AmountOfChargeTonew.this, getString(R.string.get_prepayid_fail), Toast.LENGTH_LONG)
						.show();
			} else {
				if (result.get("status").equalsIgnoreCase("0")) // 成功
				{

					// Toast.makeText(AmountOfCharge.this,
					// R.string.get_prepayid_succ, Toast.LENGTH_LONG)
					// .show();
					RequestMsg msg = new RequestMsg();
					msg.setTokenId(result.get("token_id"));
					// 支付宝支付
					if (type == 5) {
						msg.setTradeType(MainApplication.PAY_NEW_ZFB_WAP);
					} else {
						msg.setTradeType(MainApplication.PAY_QQ_WAP);
					}
					PayPlugin.unifiedH5Pay(AmountOfChargeTonew.this, msg);
					// resultReq.getStatus()==400或者500，resultReq.getMessage()返回对应错误信息
					// Log.i("tag", "res-->" + resultReq.getStatus() +
					// ",ressage-->" + resultReq.getMessage());

					// // 手Q wap支付
					// msg.setTradeType(MainApplication.PAY_QQ_WAP);
					// PayPlugin.unifiedH5Pay(PayMainActivity.this, msg);
					//
				} else {
					Toast.makeText(AmountOfChargeTonew.this, getString(R.string.get_prepayid_fail), Toast.LENGTH_LONG)
							.show();
				}

			}

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected Map<String, String> doInBackground(Void... params) {
			// 统一预下单接口
			String url = "https://pay.swiftpass.cn/pay/gateway";

			String entity = getParams();

			Log.d(TAG, "doInBackground, url = " + url);
			Log.d(TAG, "doInBackground, entity = " + entity);

			byte[] buf = Util.httpPost(url, entity);
			if (buf == null || buf.length == 0) {
				return null;
			}
			String content = new String(buf);
			Log.d(TAG, "doInBackground, content = " + content);
			try {
				return XmlUtils.parse(content);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}

	private String genOutTradNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String key = format.format(date);

		java.util.Random r = new java.util.Random();
		key += r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	String payOrderNo;
	public String recommendbody;// 商品名称
	public String recommendprice;// 价格
	public String recommenddes;// 商品描述
	public String recommendattach;

	/**
	 * 组装参数 <功能详细描述>
	 * 
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private String getParams() {

		Map<String, String> params = new HashMap<String, String>();
		params.put("body", recommendbody); // 商品名称
		params.put("attach", recommendattach);// 附加信息，在查询接口和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
		params.put("service", "unified.trade.pay"); // 支付类型
		params.put("version", "2.0"); // 版本

		// params.put("mch_id", mchId.getText().toString()); // 威富通商户号

		params.put("notify_url", "http://hqcz.ucaipiao.com/PayConfirm4.aspx"); // 后台通知url,默认是空格，商户测试及上线时一定要改为自己正式的
		params.put("nonce_str", genNonceStr()); // 随机数
		payOrderNo = genOutTradNo();
		params.put("out_trade_no", payOrderNo); // 订单号
		params.put("device_info", "AND_SDK"); // 应用类型
		params.put("mch_app_name", "好球cp"); // 应用名
		params.put("mch_app_id", "bls.juejin.cn"); // 包名
		params.put("mch_create_ip", "127.0.0.1"); // 机器ip地址
		params.put("total_fee", Integer.parseInt(recommendprice) * 100 + ""); // 总金额
		params.put("limit_credit_pay", "0"); // 是否限制信用卡支付， 0：不限制（默认），1：限制
		if (type == 5) {

			params.put("mch_id", "134530000080"); // 威富通商户号
			String sign = createSign("13de1f5e61338ba94f9ea2d71f53d6ed", params); // 01133be809cd03a4726e8b861b58ad7a
																					// 威富通密钥
			params.put("sign", sign); // sign签名
			Log.e("x", "支付宝支付");
		} else {
			// params.put("service", "pay.tenpay.wappay"); // 支付类型
			params.put("mch_id"  , "101540215365"); // 威富通商户号
			String sign = createSign("be08cf86af5372255a8d0dc8d7dcd8ac", params); //
			params.put("sign", sign); // sign签名
			Log.e("x", "qq钱包支付");
		}

		Log.e(TAG, recommendattach);
		System.out.println("同步" + recommendattach);

		return XmlUtils.toXml(params);
	}

	public String createSign(String signKey, Map<String, String> params) {
		StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
		SignUtils.buildPayParams(buf, params, false);
		buf.append("&key=").append(signKey);
		String preStr = buf.toString();
		String sign = "";
		// 获得签名验证结果
		try {
			sign = MD5.md5s(preStr).toUpperCase();
		} catch (Exception e) {
			sign = MD5.md5s(preStr).toUpperCase();
		}
		return sign;
	}

	public void buildPayParams(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
		List<String> keys = new ArrayList<String>(payParams.keySet());
		Collections.sort(keys);
		for (String key : keys) {
			sb.append(key).append("=");
			if (encoding) {
				sb.append(urlEncode(payParams.get(key)));
			} else {
				sb.append(payParams.get(key));
			}
			sb.append("&");
		}
		sb.setLength(sb.length() - 1);
	}

	public String urlEncode(String str) {
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (Throwable e) {
			return str;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (data == null) {
			return;
		}

		String respCode = data.getExtras().getString("resultCode");
		if (!TextUtils.isEmpty(respCode) && respCode.equalsIgnoreCase("success")) {
			// 标示支付成功
			Toast.makeText(AmountOfChargeTonew.this, "支付成功", Toast.LENGTH_LONG).show();
			finish();
		} else { // 其他状态NOPAY状态：取消支付，未支付等状态
			Toast.makeText(AmountOfChargeTonew.this, "未支付", Toast.LENGTH_LONG).show();
		}

		super.onActivityResult(requestCode, resultCode, data);

	}
}
